import { login, getInfo, getPublicKey } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import md5 from "js-md5";
import defAva from "@/assets/images/avatar.jpg";
import { encrypt, decrypt } from "@/utils/jsencrypt";
const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    id: "",
    name: "",
    avatar: "",
    projects: [],
    role: "",
    roles: [],
    permissions: [],
    areaId: null,
  }),
  actions: {
    getPublicKey() {
      return new Promise((resolve, reject) => {
        getPublicKey()
          .then((res) => {
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        this.getPublicKey().then((res) => {
          let publicKey = res.publicKey;
          const username = userInfo.username.trim();
          //调用加密方法(传密码和公钥)
          const password = encrypt(userInfo.password, publicKey);
          const code = userInfo.code;
          const uuid = userInfo.uuid;
          login(username, password, code, uuid)
            .then((res) => {
              let data = res.data;

              setToken(data.access_token);
              // window.localStorage.setItem(
              //   "AuthorizationToken",
              //   data.access_token
              // );
              this.token = data.access_token;
              resolve();
            })
            .catch((error) => {
              reject(error);
            });
        });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(async (res) => {
            const user = res.user;
            // 先用默认头像
            const avatar = defAva; // : user.avatar;
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles;
              this.permissions = res.permissions;
            } else {
              this.roles = ["ROLE_DEFAULT"];
            }
            this.id = user.userId;
            this.userName = user.userName;
            this.avatar = avatar;
            this.nickName = user.nickName;
            this.userInfo = user;
            this.areaId = user.areaId;
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        this.token = "";
        removeToken();
        window.location.reload();
        resolve();
      });
    },
  },
});

export default useUserStore;
